package com.shuoyue.ycgk.ui.mine.learnprogress;

import android.view.Gravity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.shuoyue.ycgk.BuildConfig;
import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.entity.DealLessonInfo;
import com.shuoyue.ycgk.entity.MouthInfo;
import com.shuoyue.ycgk.entity.Rule;
import com.shuoyue.ycgk.ui.common.RuleContract;
import com.shuoyue.ycgk.ui.mine.learnprogress.contract.DealClassProgressContract;
import com.shuoyue.ycgk.utils.GridSpacingItemDecoration;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.utils.XDateUtils;
import com.shuoyue.ycgk.views.SportProgressView;
import com.shuoyue.ycgk.views.dialog.common.BigHintDialog;
import com.shuoyue.ycgk.views.dialog.common.HintDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 协议班
 */
public class DealClassProgressActivity extends BaseMvpActivity<DealClassProgressContract.Presenter>
        implements DealClassProgressContract.View, RuleContract.View {


    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.days)
    TextView days;
    @BindView(R.id.minute)
    TextView minute;
    @BindView(R.id.question_num)
    TextView questionNum;
    @BindView(R.id.progress)
    SportProgressView progress;
    @BindView(R.id.rule)
    TextView rule;
    @BindView(R.id.mouth)
    TextView mouth;
    @BindView(R.id.week)
    RecyclerView weekRecycleView;
    @BindView(R.id.dday)
    RecyclerView dayRecycleView;
    @BindView(R.id.statue)
    TextView statue;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.week_minute)
    TextView weekMinute;
    @BindView(R.id.week_minute_pro)
    ProgressBar weekMinutePro;
    @BindView(R.id.week_question_num)
    TextView weekQuestionNum;
    @BindView(R.id.week_question_num_pro)
    ProgressBar weekQuestionNumPro;
    @BindView(R.id.week_record_rate)
    TextView weekRecordRate;
    @BindView(R.id.week_record_rate_pro)
    ProgressBar weekRecordRatePro;

    DealCalenderAdapter calenderAdapter;
    Calendar calendar = Calendar.getInstance();

    RuleContract.Presenter rulePresenter;

    boolean isAskingNetwork = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_deal_class_progress;
    }

    @Override
    protected void initView() {
        pageTitle.setText("协议班学习进度");
        weekRecycleView.setLayoutManager(new GridLayoutManager(mContext, 7));
        weekRecycleView.setAdapter(new WeekAdapter());
        dayRecycleView.setLayoutManager(new GridLayoutManager(mContext, 7));
        dayRecycleView.addItemDecoration(new GridSpacingItemDecoration(7,
                SizeUtil.dip2px(mContext, 8), false));
        dayRecycleView.setAdapter(new WeekAdapter());
        calenderAdapter = new DealCalenderAdapter(null);
        calenderAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (!isAskingNetwork) {
                DayInfo dayInfo = calenderAdapter.getItem(position);
                for (DayInfo dayInfoAll : calenderAdapter.getData()) {
                    dayInfoAll.setSelect(false);
                }
                dayInfo.setSelect(true);
                calenderAdapter.notifyDataSetChanged();
                Calendar tagerCal = Calendar.getInstance();
                tagerCal.setTime(dayInfo.getData());

                getInfo(XDateUtils.format(tagerCal.getTimeInMillis(), "yyyy-MM-dd"));//tagerCal.get(Calendar.YEAR)
//                        + "-"
//                        + (tagerCal.get(Calendar.MONTH) + 1)
//                        + "-"
//                        + tagerCal.get(Calendar.DAY_OF_MONTH));
                time.setText(tagerCal.get(Calendar.YEAR)
                        + "-"
                        + (tagerCal.get(Calendar.MONTH) + 1)
                        + "-"
                        + tagerCal.get(Calendar.DAY_OF_MONTH));
                selectYear = tagerCal.get(Calendar.YEAR);
                selectmonth = tagerCal.get(Calendar.MONTH);
                selectdayOmonth = dayInfo.getDayInMouth();

            }
        });
        time.setText(calendar.get(Calendar.YEAR)
                + "-"
                + (calendar.get(Calendar.MONTH) + 1)
                + "-"
                + calendar.get(Calendar.DAY_OF_MONTH));
        progress.setProgress(0);

    }

    @Override
    public void initData() {
        mPresenter = new DealClassProgressContract.Presenter();
        mPresenter.attachView(this);
        rulePresenter = new RuleContract.Presenter();
        rulePresenter.attachView(this);
        dayRecycleView.setAdapter(calenderAdapter);
        mouth.setText(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1));
        setDayAdapter(false, true);
        mPresenter.getMouthInfos(new Date(calendar.getTimeInMillis()));
        getInfo(XDateUtils.format(calendar.getTimeInMillis(), "yyyy-MM-dd"));
    }

    private void getInfo(String date) {
        isAskingNetwork = true;
        mPresenter.getProgressInfo(date);
    }

    @OnClick({R.id.back, R.id.last_mouth, R.id.next_mouth, R.id.next_week, R.id.rule})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rule:
                rulePresenter.getRule(3);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.last_mouth:
                calendar.add(Calendar.MONTH, -1);
                setDayAdapter(false, false);
                mPresenter.getMouthInfos(new Date(calendar.getTimeInMillis()));
                break;
            case R.id.next_mouth:
                calendar.add(Calendar.MONTH, 1);
                setDayAdapter(false, false);
                mPresenter.getMouthInfos(new Date(calendar.getTimeInMillis()));
                break;
            case R.id.next_week:
                setDayAdapter(true, false);
                mPresenter.getMouthInfos(new Date(calendar.getTimeInMillis()));
                break;
        }
    }

    private void setDayAdapter(boolean isSwitch, boolean isFirst) {
        mouth.setText(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1));
        if (isFirst) {
            calenderAdapter.resetData(getDayInfos(1,
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH)));
        } else if (isSwitch) {
            if (calenderAdapter.getItemCount() > 7) {
                calenderAdapter.resetData(getDayInfos(1,
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH)));
            } else {
                calenderAdapter.resetData(getDayInfos(2,
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH)));
            }
        } else {
            if (calenderAdapter.getItemCount() > 7) {
                calenderAdapter.resetData(getDayInfos(2,
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH)));
            } else {
                calenderAdapter.resetData(getDayInfos(1,
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH)));
            }
        }
    }

    /**
     * @param type 1:week   2:mouth
     * @return
     */
    int selectYear;//选中
    int selectmonth;
    int selectdayOmonth;

    private List<DayInfo> getDayInfos(int type, int year, int mouth) {
        Calendar calendarNow = Calendar.getInstance(Constant.timeZone);
        int nowyear = calendarNow.get(Calendar.YEAR);
        int nowmonth = calendarNow.get(Calendar.MONTH);
        int nowdayOmonth = calendarNow.get(Calendar.DAY_OF_MONTH);
        if (selectYear == 0 && selectdayOmonth == 0 && selectmonth == 0) {
            selectYear = nowyear;
            selectmonth = nowmonth;
            selectdayOmonth = nowdayOmonth;
        }
        Calendar calendar = Calendar.getInstance(Constant.timeZone);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, mouth);
        List<DayInfo> dayInfos = new ArrayList<>();
        if (type == 1) {
            //本周一组数据
            //找到第一天
            int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); //星期天开始1-7
            calendar.add(Calendar.DAY_OF_MONTH, -day_of_week + 1);
            for (int i = 0; i < 7; i++) {
                DayInfo dayInfo = new DayInfo();
                dayInfo.setData(calendar.getTime());
                dayInfo.setDayInMouth(calendar.get(Calendar.DAY_OF_MONTH));
                dayInfos.add(dayInfo);
                if (selectYear == calendar.get(Calendar.YEAR)
                        && selectmonth == calendar.get(Calendar.MONTH)
                        && selectdayOmonth == calendar.get(Calendar.DAY_OF_MONTH)) {
                    dayInfo.setSelect(true);
                }
                calendar.add(Calendar.DAY_OF_WEEK, 1);
            }
        } else {
            int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);//要显示的数量
            //设置日期未最后一天
            calendar.set(Calendar.DAY_OF_MONTH, maxDay);
            int dayOfWeekEndAdd = 7 - calendar.get(Calendar.DAY_OF_WEEK);


            //设置日期为1号
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            int dayOfWeekStartSub = calendar.get(Calendar.DAY_OF_WEEK) - 1;

            //循环走到最后一个星期六
            calendar.add(Calendar.DAY_OF_MONTH, -dayOfWeekStartSub);
            int maxDaysUI = maxDay + dayOfWeekEndAdd + dayOfWeekStartSub;
            for (int i = 0; i < maxDaysUI; i++) {
                DayInfo dayInfo = new DayInfo();
                dayInfo.setData(calendar.getTime());
                dayInfo.setDayInMouth(calendar.get(Calendar.DAY_OF_MONTH));
                dayInfos.add(dayInfo);
                if (selectYear == calendar.get(Calendar.YEAR)
                        && selectmonth == calendar.get(Calendar.MONTH)
                        && selectdayOmonth == calendar.get(Calendar.DAY_OF_MONTH)) {
                    dayInfo.setSelect(true);
                }
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
        return dayInfos;
    }

    @Override
    public void setLessonProcess(DealLessonInfo lessonProcess) {
        isAskingNetwork = false;
        if (lessonProcess == null) {
            return;
        }

        days.setText(String.valueOf(lessonProcess.getSumDays()));
        minute.setText(String.valueOf(lessonProcess.getSumMinutes()));
        questionNum.setText(String.valueOf(lessonProcess.getSumQuestions()));
        weekMinute.setText(String.valueOf(lessonProcess.getTargetOfDayDTO().getMinuteNum()));
        weekQuestionNum.setText(String.valueOf(lessonProcess.getTargetOfDayDTO().getQuestionNum()));
        weekRecordRate.setText(lessonProcess.getTargetOfDayDTO().getAccuracy() + "%");
        progress.setProgress(lessonProcess.getDonePercent());
        weekMinutePro.setProgress(lessonProcess.getTargetOfDayDTO().getMinutePercent());
        weekQuestionNumPro.setProgress(lessonProcess.getTargetOfDayDTO().getQuestionPercent());
        weekRecordRatePro.setProgress(lessonProcess.getTargetOfDayDTO().getAccuracyPercent());
        statue.setBackgroundResource(lessonProcess.getTargetOfDayDTO().getIsDone() == 1 ?
                R.mipmap.deal_finished : R.mipmap.deal_not_finish);
        statue.setText(lessonProcess.getTargetOfDayDTO().getIsDone() == 1 ? "已完成" : "未完成");
        if (calenderAdapter.getCalendarStart() == null) {
            calenderAdapter.setStartDate(lessonProcess.getJoinDate());
        }
        if (calenderAdapter.getCalendarEnd() == null) {
            calenderAdapter.setEndDate(lessonProcess.getEndDate());
        }
    }

    @Override
    public void setMouthInfo(Date date, List<MouthInfo> infos) {
        Calendar tagetCal = Calendar.getInstance();
        tagetCal.setTime(date);
        if (tagetCal.get(Calendar.YEAR) == calendar.get(Calendar.YEAR)
                && tagetCal.get(Calendar.MONTH) == calendar.get(Calendar.MONTH)) {
            for (DayInfo dayInfo : calenderAdapter.getData()) {
                for (MouthInfo m : infos) {
                    if (dayInfo.getDayInMouth() == m.getDay()) {
                        dayInfo.setIsDone(m.getIsDone());
//                        if (BuildConfig.DEBUG) {
//                            dayInfo.setIsDone(1);
//                        }
                        break;
                    }
                }
            }
            calenderAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setRule(Rule userInfo) {
        BigHintDialog hintDialog = new BigHintDialog(mContext, "协议班规则",
                userInfo.getContent(), Gravity.LEFT);
        hintDialog.show();
    }
}
